<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="标签名称" prop="tagName">
        <el-input v-model="formData.tagName" placeholder="请输入标签名称" />
      </el-form-item>
      <el-form-item label="标签代码" prop="tagCode">
        <el-input v-model="formData.tagCode" placeholder="请输入标签代码" />
      </el-form-item>
      <el-form-item label="标签备注" prop="tagRemark">
        <el-input v-model="formData.tagRemark" placeholder="请输入标签备注" />
      </el-form-item>
			<el-form-item label="标签启用状态" prop="enabled">
			  <el-select v-model="formData.enabled" placeholder="请选择状态">
					<el-option label='开启' :value='true' />
					<el-option label='关闭' :value='false' />
			    <!-- <el-option
			      v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
			      :key="parseInt(dict.value as any)"
			      :label="dict.label"
			      :value="!!(dict.value as any)"
			    /> -->
			  </el-select>
			</el-form-item>
    </el-form>
		<el-table :data="formData.tagUsers" class="-mt-10px">
		  <el-table-column label="序号" type="index" width="100" />
		  <el-table-column label="姓名" prop="nickname" >
				<template #default="scope">
				  {{scope.row.nickname || scope.row.userSimpleRespVO?.nickname}}
				</template>
			</el-table-column>
		  <el-table-column label="部门" prop="deptName" >
				<template #default="scope">
				  {{scope.row.deptName || scope.row.userSimpleRespVO?.deptName}}
				</template>
		  </el-table-column>
		  <el-table-column align="center" fixed="right" label="操作" width="60">
		    <template #default="{ $index }">
		      <el-button @click="handleDelete($index)" link>—</el-button>
		    </template>
		  </el-table-column>
		</el-table>
		<el-row justify="center" class="mt-3">
		  <el-button type="primary" link @click="openStartUserSelect">
		    <Icon icon="ep:plus" /> 添加人员
		  </el-button>
		</el-row>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
		<!-- 用户选择弹窗 -->
  </Dialog>
	<UserSelectForm ref="userSelectFormRef" @confirm="handleUserSelectConfirm" />
</template>
<script setup lang="ts">
import { UserVO } from '@/api/system/user'

import { ReportingTagApi, ReportingTag } from '@/api/system/reportingtag'
import { ReportingTagUserApi } from '@/api/system/reportingtaguser/index'

/** 汇报标签 表单 */
defineOptions({ name: 'ReportingTagForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const selectedTagtUsers = ref([])
const userSelectFormRef = ref()
const formData = ref({
  id: undefined,
  tagName: undefined,
  tagCode: undefined,
  tagRemark: undefined,
  enabled: true,
	tagUsers:[]
})
const formRules = reactive({
  tagName: [{ required: true, message: '标签名称不能为空', trigger: 'blur' }],
  tagCode: [{ required: true, message: '标签代码不能为空', trigger: 'blur' }],
  enabled: [{ required: true, message: '标签启用状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref


/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ReportingTagApi.getReportingTag(id)
			formData.value.tagUsers = await ReportingTagUserApi.list({
				pageNo: 1,
				pageSize: 100,
				tagId: id}
				)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ReportingTag
    if (formType.value === 'create') {
      await ReportingTagApi.createReportingTag(data)
      message.success(t('common.createSuccess'))
    } else {
      await ReportingTagApi.updateReportingTag(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
// 删除
const handleDelete = (index)=>{
	formData.value.tagUsers.splice(index,1)
}
/** 打开发起人选择 */
const openStartUserSelect = () => {
  userSelectFormRef.value.open(0, selectedTagtUsers.value,true)
}
/** 处理用户选择确认 */
const handleUserSelectConfirm = (_, users: UserVO[]) => {
	users.forEach((u)=>{
		let current = formData.value.tagUsers.find(i=>{
			return u.id === i.id
		})
		if(!current){
			let user = JSON.parse(JSON.stringify(u))
			user.tagId = formData.value.id
			user.userId = u.id
			delete user.id
			formData.value.tagUsers.push(user)
		}
	})
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    tagName: undefined,
    tagCode: undefined,
    tagRemark: undefined,
    enabled: true,
		tagUsers:[]
  }
  formRef.value?.resetFields()
}
</script>